package org.zhxy.zhxy.controller.front;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.zhxy.zhxy.service.UserService;
import org.zhxy.zhxy.utils.Result;

import javax.annotation.Resource;

@RestController
@RequestMapping("/api/wx")
public class WxLoginController {
    String appId="wxe6d461d1994db1a0";
    String secret="00630d66edb447e3c9dff8712042de76";

    private RestTemplate restTemplate =new RestTemplate();
    @Resource
    private UserService userService;
    @PostMapping("/login")
    public Result login(String code){
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
        String body = forEntity.getBody();
        JSONObject entries = JSONUtil.parseObj(body);

        String openid = entries.getStr("openid");
        System.out.println(openid+"hhhh"+code);
        String token =  userService.loginByWx(openid);
        return Result.success(token);

    }



    /**
     * 绑定openid
     */
    @PostMapping("/bind-openid")
    public Result bindOpenId(String code){
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
        //
        String body = forEntity.getBody();
        JSONObject entries = JSONUtil.parseObj(body);
        String openId = entries.getStr("openid");
        userService.bindOpenId(openId);
        return Result.success();
    }
    @PostMapping("/unbind-openid")
    public  Result unbindOpenId()
    {
        userService.unbindOpenId();
        return  Result.success();
    }
}
